<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .router-link-active {
      background-color: red;
    }
  </style>
</head>

<body>
  <div id="app">
    <router-link tag="button" to="/home">首页</router-link>
    <router-link tag="button" to="/news">新闻</router-link>
    <router-link tag="button" to="/about">关于</router-link>
    <hr>
    <router-view></router-view>
  </div>
  <script src="./vue.js"></script>
  <script src="./vue-router.js"></script>
  <script>
    const Home = {
      template: `
        <div>
          <h2>我是首页</h2>  
        </div>
      `
    }
    const News = {
      template: `
        <div>
          <h2>我是新闻页</h2>  
        </div>
      `
    }
    const About = {
      template: `
        <div>
          <h2>我是关于我们</h2>  
        </div>
      `
    }
    const Login = {
      template: `
        <div>
          <h2>登录页</h2>  
          <button @click="login">点击登录</button>
        </div>
      `,
      mounted() {
        console.log(this.$route);
      },
      methods: {
        login() {
          setTimeout(() => {
            const token = 'fdiefhi98rfihcdfheihcd';
            // 将登录接口返回 token 存储起来
            localStorage.setItem("access_token", token);
            // 登录成功后
            this.$router.replace(this.$route.query.from)
          }, 2000)
        }
      }
    }
    const routes = [ // 定义路由规则
      {
        path: '/',
        redirect: '/home'
      },
      {
        path: '/home',
        name: "home",
        meta:{
          needLogin: false
        },
        component: Home
      },
      {
        path: '/news',
        name: 'news',
        meta:{
          needLogin: false
        },
        component: News
      },
      {
        path: '/about',
        name: 'about',
        meta:{
          needLogin: true
        },
        component: About
      },
      {
        path: '/login',
        name: 'login',
        meta:{
          needLogin: false
        },
        component: Login
      }
    ]
    // 创建路由对象
    const router = new VueRouter({
      routes
    });
    /* 
    路由前置守卫
    拦截所有的路由
    前置：路由进入之前拦截
    */
    router.beforeEach((to, from, next) => {
      /* 
      获取 to 的meta 下needLogin 真 需要登录 假不需要登录
      判断用户是否登录
        判断token是否存在
          存在
            放行
          不存在
            跳转到登录
      */
      if(!to.meta.needLogin){
        next();
      }else{
        // 需要登录
        const token = localStorage.getItem('access_token');
        if(token){
          // 登录了
          next();
        }else{
          // 没有登录
          next({
            path:'/login',
            query:{
              from: to.path
            }
          })
        }
      }
    })
    const vm = new Vue({
      el: "#app",
      router
    })
  </script>
</body>

</html>